package io.lvdaxian.mybatis07.transaction.jdbc;


import io.lvdaxian.mybatis07.session.TransactionIsolationLevel;
import io.lvdaxian.mybatis07.transaction.Transaction;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 实现 事务接口的 jdbc 事务
 *
 * @author lihh
 */
public class JdbcTransaction implements Transaction {
  
  protected Connection connection;
  protected DataSource dataSource;
  protected TransactionIsolationLevel level = TransactionIsolationLevel.NONE;
  // 表示 事务的自动提交
  protected boolean autoCommit;
  
  public JdbcTransaction(DataSource dataSource, TransactionIsolationLevel transactionIsolationLevel, boolean autoCommit) {
    this.dataSource = dataSource;
    this.level = transactionIsolationLevel;
    this.autoCommit = autoCommit;
  }
  
  public JdbcTransaction(Connection connection) {
    this.connection = connection;
  }
  
  /**
   * 通过该方法 获取 Connection
   *
   * @return 返回 Connection 连接
   * @author lihh
   */
  @Override
  public Connection getConnection() throws SQLException {
    connection = dataSource.getConnection();
    connection.setTransactionIsolation(level.getLevel());
    connection.setAutoCommit(autoCommit);
    return connection;
  }
  
  private boolean isNotAutoCommit() throws SQLException {
    if (null != connection && !connection.getAutoCommit())
      return true;
    return false;
  }
  
  @Override
  public void commit() throws SQLException {
    // 根据 Connection 提交 commit 事务
    if (isNotAutoCommit())
      connection.commit();
  }
  
  @Override
  public void rollback() throws SQLException {
    if (isNotAutoCommit())
      connection.rollback();
  }
  
  @Override
  public void close() throws SQLException {
    if (isNotAutoCommit())
      connection.close();
  }
}
